package com.cqhz.quwan.ui.main.adapter

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.bigkoo.convenientbanner.ConvenientBanner
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator
import com.bigkoo.convenientbanner.holder.Holder
import com.blankj.utilcode.util.ObjectUtils.isEmpty
import com.blankj.utilcode.util.StringUtils
import com.chad.library.adapter.base.BaseViewHolder
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.BannerItem
import com.cqhz.quwan.model.news.NewsBannerBean
import com.cqhz.quwan.model.news.NewsBaseBean
import com.cqhz.quwan.model.news.NewsInfoBean
import com.cqhz.quwan.model.news.NewsMatchBean
import com.cqhz.quwan.ui.base.WebViewActivity
import com.cqhz.quwan.util.*

class NewsMixAdapter(context: Context, activity: Activity, data: List<NewsBaseBean>) : BaseMixQuickAdapter<NewsBaseBean, BaseViewHolder>(data) {

    private var context: Context = context
    private var activity: Activity = activity

    init {
        addItemLayout()
    }

    /**
     * 绑定不同布局
     */
    private fun addItemLayout() {
        addItemType(1, R.layout.layout_page_banner)
        addItemType(2, R.layout.layout_page_news_match)
        addItemType(3, R.layout.layout_page_news_info)
    }


    override fun convert(helper: BaseViewHolder, item: NewsBaseBean) {
        when (helper.itemViewType) {
            1 -> setAD(helper, item as NewsBannerBean)
            2 -> setMatch(helper, item as NewsMatchBean)
            3 -> setNews(helper, item as NewsInfoBean)
        }
    }

    /**
     * 设置顶部广告
     * @param helper
     * @param item
     */
    private fun setAD(helper: BaseViewHolder, item: NewsBannerBean) {
        val cbAd = helper.getView(R.id.cb_ad) as ConvenientBanner<BannerItem>
        val params = cbAd.layoutParams as ViewGroup.LayoutParams
        params.height = activity.getScreenWidth() * 300 / 750
        cbAd.layoutParams = params
        if (item.getList().isEmpty()) {
            params.height = 1
            cbAd.layoutParams = params
            return
        }

        cbAd.setPages(object : CBViewHolderCreator {
            override fun createHolder(itemView: View): ImageHolderView {
                return ImageHolderView(itemView, context)
            }

            override fun getLayoutId(): Int {
                return R.layout.item_image_view
            }
        }, item.getList()).setOnItemClickListener { position ->
            val bi = item.getList()[position]
            if (!StringUtils.isEmpty(bi.linkUrl)) {
                val url = Tools.urlCV(bi.linkUrl)
                val intent = Intent(context, WebViewActivity::class.java)
                intent.putExtra(KeyContract.Url, url)
                intent.putExtra(KeyContract.BannerId, bi.id)
                intent.putExtra(KeyContract.Title, "活动")
                intent.putExtra(KeyContract.EnableRefresh, false)
                context.startActivity(intent)
            }
        }

        if (!cbAd.isTurning && item.getList().size > 1) {
            cbAd.setPageIndicator(intArrayOf(R.drawable.banner_btn_n, R.drawable.banner_btn_s))
                    .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                    .startTurning(5000)
        }
    }

    /**
     * 设置赛事
     * @param helper
     * @param item
     */
    private fun setMatch(helper: BaseViewHolder, item: NewsMatchBean) {
        var list = item.getList()
        if (isEmpty(list)) {
            return
        }
        // 设置比赛数据
        helper.setText(R.id.tv_game1_name, list!![0].league)
        helper.setText(R.id.tv_game2_name, list!![1].league)
        helper.setText(R.id.tv_game1_time, when (list!![0].status) {
            "0" -> "今天" + list!![0].matchTime.formatTime("HH:mm")
            "1" -> "进行中"
            "2" -> "暂停"
            "3" -> "已结束"
            "4" -> "推迟"
            "5" -> "已取消"
            else -> {
                "其他"
            }
        })
        helper.setText(R.id.tv_game2_time, when (list!![1].status) {
            "0" -> "今天" + list!![1].matchTime.formatTime("HH:mm")
            "1" -> "进行中"
            "2" -> "暂停"
            "3" -> "已结束"
            "4" -> "推迟"
            "5" -> "已取消"
            else -> {
                "其他"
            }
        })

        helper.setText(R.id.tv_game1_host_name, list!![0].hostTeam)
        helper.setText(R.id.tv_game1_guest_name, list!![0].guestTeam)
        helper.setText(R.id.tv_game2_host_name, list!![1].hostTeam)
        helper.setText(R.id.tv_game2_guest_name, list!![1].guestTeam)


        if (!StringUtils.isEmpty(list!![0].score)) {
            var score1 = list!![0].score.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
            helper.setText(R.id.tv_game1_host_score, score1[0])
            helper.setText(R.id.tv_game1_guest_score, score1[1])
        } else {
            helper.setText(R.id.tv_game1_host_score, "0")
            helper.setText(R.id.tv_game1_guest_score, "0")
        }
        if (!StringUtils.isEmpty(list!![1].score)) {
            var score2 = list!![1].score.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
            helper.setText(R.id.tv_game2_host_score, score2[0])
            helper.setText(R.id.tv_game2_guest_score, score2[1])
        } else {
            helper.setText(R.id.tv_game2_host_score, "0")
            helper.setText(R.id.tv_game2_guest_score, "0")
        }

        // 赛事状态0：未开始 1：进行中 2：暂停 3：已完成 4：推迟 5：取消
        helper.setImageResource(R.id.iv_game1_bg, if ("3" == list[0].status || "5" == list[0].status) R.drawable.img_end else R.drawable.img_begin)
        helper.setImageResource(R.id.iv_game2_bg, if ("3" == list[1].status || "5" == list[1].status) R.drawable.img_end else R.drawable.img_begin)
        helper.setImageResource(R.id.iv_game1_host_flag, if ("3" == list[1].status || "5" == list[1].status) R.drawable.img_end else R.drawable.img_begin)

        helper.getView<ImageView>(R.id.iv_game1_host_flag).setLoadImage(this!!.context!!, list[0].hostLogo, R.drawable.team_ic_default)
        helper.getView<ImageView>(R.id.iv_game1_guest_flag).setLoadImage(this!!.context!!, list[0].guestLogo, R.drawable.team_ic_default)
        helper.getView<ImageView>(R.id.iv_game2_host_flag).setLoadImage(this!!.context!!, list[1].hostLogo, R.drawable.team_ic_default)
        helper.getView<ImageView>(R.id.iv_game2_guest_flag).setLoadImage(this!!.context!!, list[1].guestLogo, R.drawable.team_ic_default)

        helper.addOnClickListener(R.id.action_goto_match1)
        helper.addOnClickListener(R.id.action_goto_match2)
    }

    /**
     * 设置新闻列表
     * @param helper
     * @param item
     */
    private fun setNews(helper: BaseViewHolder, item: NewsInfoBean) {
        var news = item.getNewsBean()
        (helper.getView(R.id.iv_news) as ImageView).setLoadImage(activity, news!!.titlePic, R.drawable.mall_img_default)
        helper.setText(R.id.tv_news_title, news!!.title)
        helper.setText(R.id.tv_news_source, news!!.source)
        helper.setText(R.id.tv_reading_number, news!!.clickNums.toString())
        helper.setGone(R.id.line, helper.adapterPosition < data.size - 1)
    }

    /**
     * 图片轮转实现
     */
    internal class ImageHolderView(itemView: View, private val context: Context) : Holder<BannerItem>(itemView) {
        private var imageView: ImageView? = null

        override fun initView(itemView: View) {
            imageView = itemView.findViewById(R.id.imageView)
            imageView!!.scaleType = ImageView.ScaleType.FIT_XY
        }

        override fun updateUI(item: BannerItem) {
            imageView!!.setLoadImage(context, item.imgUrl, 0)
        }
    }

    override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
        when (holder.itemViewType) {
            in 1..3 -> setFullSpan(holder)
        }

        super.onBindViewHolder(holder, position)
    }
}